<script setup lang="ts">
import http from '@/tools/http'
import type { DataTableColumns, DataTableRowKey } from 'naive-ui'
import { NButton, NDataTable, NDatePicker, NForm, NFormItem, NInput, NPagination, NSpace, NModal, useNotification, NTag } from 'naive-ui'
import { h, onMounted, reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { useDictStore } from '@/stores/dictStore'
import UserSelector from '../component/user-selector/index.vue'

const router = useRouter()
const notification = useNotification()
const dictStore = useDictStore()

type RowData = {
    userTaskId?: string
    instanceId: string
    instanceName?: string
    modelId?: string
    modelVersion?: string
    taskId: string
    taskName?: string
    taskType?: string
    userTaskStatus: string
    objType?: string
    objId?: string
    userId?: string
    userName?: string
    createTime?: string
}

const rowKeys = ref<DataTableRowKey[]>([])

const userTaskTableColumns: DataTableColumns<RowData> = [
    {
        title: "流程名称",
        key: "instanceName",
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "任务名称",
        key: "taskName",
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "提交人",
        key: "userName",
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "处理结果",
        key: "userTaskStatus",
        render(rowData: RowData, rowIndex: number) {
            let type: "default" | "error" | "primary" | "info" | "success" | "warning" = "default"
            if (["0", "3", "4"].includes(rowData.userTaskStatus)) {
                type = "info"
            }
            if (rowData.userTaskStatus === "1") {
                type = "error"
            }
            if (["2", "5", "6"].includes(rowData.userTaskStatus)) {
                type = "success"
            }
            return h(
                NTag,
                {
                    type: type
                },
                dictStore.dictItem("WORKFLOW_USER_TASK_STATUS", rowData.userTaskStatus)
            )
        },
    }, {
        title: "提交时间",
        key: "createTime",
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "完成时间",
        key: "endTime",
        ellipsis: {
            tooltip: true
        }
    }, {
        title: "操作",
        key: "actions",
        fixed: 'right',
        render(rowData: RowData, rowIndex: number) {
            return h(
                NSpace, null,
                () => [
                    h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openFlowProcess(rowData)
                        },
                        { default: () => "查看" }
                    ),
                    h(
                        NButton,
                        {
                            size: "small",
                            onclick: () => openCopySendForm(rowData)
                        },
                        { default: () => "抄送" }
                    )
                ]
            )
        }
    }
]

const userTaskData = reactive<any>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    pages: 1,
    total: 0
})

const userTaskSearchFormValue = reactive({
    pageNum: 1,
    pageSize: 10,
    instanceName: "",
    userName: "",
    createTimeRange: undefined
})

const approveFormVisiable = ref<boolean>(false)

const copySendFormVisiable = ref<boolean>(false)

const copySendForm = reactive<{
    instanceId: string
    taskId: string
    userIdSet: string[]
    message: string
}>({
    instanceId: "",
    taskId: "",
    userIdSet: [],
    message: ""
})

onMounted(() => {
    pageUserTask()
})

function openCopySendForm(rowData: RowData) {
    copySendForm.instanceId = rowData.instanceId
    copySendForm.taskId = rowData.taskId
    copySendForm.userIdSet.length = 0
    copySendFormVisiable.value = true
}

function pageNumChange(pageNum: number) {
    userTaskSearchFormValue.pageNum = pageNum
    pageUserTask()
}

function pageSizeChange(pageSize: number) {
    userTaskSearchFormValue.pageSize = pageSize
    pageUserTask()
}

function openFlowProcess(rowData: RowData) {
    router.push({
        name: "workflow-info",
        query: {
            instanceId: rowData.instanceId,
            modelId: rowData.modelId,
            modelVersion: rowData.modelVersion,
            mode: "4",
            taskId: rowData.taskId
        }
    })
}

function pageUserTask() {
    let start = ""
    let end = ""
    if (userTaskSearchFormValue.createTimeRange) {
        start = userTaskSearchFormValue.createTimeRange[0]
        end = userTaskSearchFormValue.createTimeRange[1]
    }
    const request = {
        pageNum: userTaskSearchFormValue.pageNum,
        pageSize: userTaskSearchFormValue.pageSize,
        instanceName: userTaskSearchFormValue.instanceName,
        userName: userTaskSearchFormValue.userName,
        userTaskStatus: "1",
        createTimeStart: start,
        createTimeEnd: end
    }
    http.post("/workflow/ru/user/task/page", request).then(({ data }) => {
        if (data.code === "0") {
            userTaskData.pageNum = data.data.pageNum
            userTaskData.pageSize = data.data.pageSize
            userTaskData.pages = data.data.pages
            userTaskData.total = data.data.total
            userTaskData.list.length = 0
            for (let i = 0; i < data.data.list.length; i++) {
                userTaskData.list.push(data.data.list[i])
            }
            rowKeys.value.length = 0
        }
    })
}

function copySendFormSubmit(userIdList: string[]) {
    if (userIdList.length > 0) {
        copySendForm.userIdSet = userIdList
        http.post("/workflow/ru/user/task/copy-send", copySendForm).then(({ data }) => {
            if (data.code === "0") {
                copySendFormVisiable.value = false
                notification['success']({
                    content: '抄送成功',
                    meta: `${data.msg}`,
                    duration: 2500,
                    keepAliveOnHover: true
                })
            }
        })
    }
}
</script>

<template>
    <div id="flame-container">
        <div class="search">
            <n-form :model="userTaskSearchFormValue" inline label-placement="left">
                <n-form-item label="流程名称" path="instanceName">
                    <n-input v-model:value="userTaskSearchFormValue.instanceName" placeholder="请输入流程名称" clearable />
                </n-form-item>
                <n-form-item label="提交人名称" path="userName">
                    <n-input v-model:value="userTaskSearchFormValue.userName" placeholder="请输入提交人名称" clearable />
                </n-form-item>
                <n-form-item label="提交时间">
                    <n-date-picker v-model:formatted-value="userTaskSearchFormValue.createTimeRange" type="daterange"
                        placeholder="请选择日期范围" clearable />
                </n-form-item>
                <n-form-item>
                    <n-button attr-type="button" @click="pageUserTask()">查询</n-button>
                </n-form-item>
            </n-form>
        </div>
        <div class="btn-group">
            <n-button attr-type="button" :disabled="rowKeys.length === 0"
                @click="approveFormVisiable = true">批量处理</n-button>
        </div>
        <div class="data-table">
            <n-data-table :scrollbar-props="{ trigger: 'none' }" style="height:100%" flex-height
                :columns="userTaskTableColumns" :data="userTaskData.list" :row-key="(row: RowData) => row.taskId"
                v-model:checked-row-keys="rowKeys" :bordered="false" />
        </div>
        <div class="pagination">
            <n-pagination style="float:right" v-model:page="userTaskData.pageNum" :page-size="userTaskData.pageSize"
                :item-count="userTaskData.total" :page-sizes="[5, 10, 30, 50, 100]" :on-update-page="pageNumChange"
                :on-update-page-size="pageSizeChange" show-quick-jumper show-size-picker />
        </div>
    </div>
    <n-modal v-model:show="copySendFormVisiable">
        <user-selector :value="copySendForm.userIdSet" title="转交流程" @update:value="copySendFormSubmit">
            <n-form-item style="margin-top:8px" label="备注信息" path="rollbackMessage">
                <n-input v-model:value="copySendForm.message" type="textarea" placeholder="请输入备注信息" />
            </n-form-item>
        </user-selector>
    </n-modal>
</template>

<style scoped></style>